﻿using ArcGIS.Core.CIM;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Extensions;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Layouts;
using CCTool.Scripts.Manager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing.Imaging;
using Button = ArcGIS.Desktop.Framework.Contracts.Button;
using MessageBox = ArcGIS.Desktop.Framework.Dialogs.MessageBox;
using System.Windows.Forms;
using ArcGIS.Desktop.Mapping;
using Microsoft.Office.Core;
using ArcGIS.Core.Data.DDL;
using FieldDescription = ArcGIS.Core.Data.DDL.FieldDescription;
using Row = ArcGIS.Core.Data.Row;
using ArcGIS.Desktop.Editing.Attributes;
using System.Security.Cryptography;
using ArcGIS.Desktop.Editing.Templates;
using ArcGIS.Core.Internal.CIM;
using System.Windows.Input;
using System.Windows.Media.Media3D;
using System.Net;
using System.Net.Http;
using System.Windows.Media;
using System.Windows.Shapes;
using Path = System.IO.Path;
using ArcGIS.Desktop.Internal.Catalog.Wizards;
using ArcGIS.Desktop.Internal.Layouts.Utilities;
using System.Windows.Documents;
using ActiproSoftware.Windows;
using System.Windows;
using System.Runtime.InteropServices;
using ArcGIS.Desktop.Internal.Mapping.Locate;
using ArcGIS.Desktop.Core.Geoprocessing;
using ArcGIS.Desktop.GeoProcessing;
using Geometry = ArcGIS.Core.Geometry.Geometry;
using Polygon = ArcGIS.Core.Geometry.Polygon;
using ArcGIS.Core.Data.Exceptions;
using Table = ArcGIS.Core.Data.Table;
using SpatialReference = ArcGIS.Core.Geometry.SpatialReference;
using System.Drawing;
using Brushes = System.Windows.Media.Brushes;
using CCTool.Scripts.ToolManagers;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using static System.Windows.Forms.MonthCalendar;
using ArcGIS.Core.Data.UtilityNetwork.Trace;
using Aspose.Cells.Drawing;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using NPOI.XWPF.UserModel;
using Aspose.Cells;
using Aspose.Words;
using CCTool.Scripts.CusTool2;
using CCTool.Scripts.ToolManagers.Managers;
using Document = Aspose.Words.Document;
using CCTool.Scripts.ToolManagers.Extensions;
using NPOI.OpenXmlFormats.Vml;
using static System.Runtime.InteropServices.JavaScript.JSType;
using System.Security.Policy;
using QueryFilter = ArcGIS.Core.Data.QueryFilter;
using NPOI.SS.Formula.PTG;

namespace CCTool.Scripts.UI.ProButton
{
    internal class TestButton5 : Button
    {
        // 定义一个进度框
        private ProcessWindow processwindow = null;

        protected override async void OnClick()
        {

            // 获取参数
            string def_folder = Project.Current.HomeFolderPath;     // 工程默认文件夹位置
            string def_gdb = Project.Current.DefaultGeodatabasePath;    // 工程默认数据库

            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, "进度");
                pw.AddMessageTitle("XXX");

                await QueuedTask.Run(() =>
                {
                    pw.AddMessageStart("检查数据");

                    // 单位系数设置
                    string unit = "公顷";
                    double unit_xs = unit switch
                    {
                        "平方米" => 1,
                        "公顷" => 10000,
                        "平方公里" => 1000000,
                        "亩" => 666.66667,
                        _ => 1,
                    };

                    // 复制嵌入资源中的Excel文件
                    string model = @$"C:\Users\Administrator\Desktop\可开发用地.xlsx";
                    string excel_path = @$"D:\【工作项目】\【策划项目】\莆田枫亭经济开发区工业提升\2-文本\可开发用地.xlsx";

                    if (File.Exists(excel_path))
                    {
                        File.Delete(excel_path);
                    }
                    File.Copy(model, excel_path);

                    // 如果分区域
                    bool isZone = true;
                    string yd = "可开发用地分析";
                    string zone = "规划范围";
                    string zoneField = "QKBH";

                    string bmList = "标记";
                    string areaField = "Shape_Area";
                    int digit = 2;



                    if (isZone)
                    {
                        string clip = $@"{def_gdb}\clip";

                        pw.AddMessageMiddle(20, $"分区域统计");
                        FeatureLayer featureLayer = zone.TargetFeatureLayer();
                        using RowCursor rowCursor = featureLayer.Search();
                        while (rowCursor.MoveNext())
                        {
                            Feature feature = rowCursor.Current as Feature;
 

                            string dkbh = feature["QKBH"]?.ToString();
                            string dkName = feature["分区名称"]?.ToString();
                            double area = (double)feature["shape_area"]/10000;

                            pw.AddMessageMiddle(0, $"     {dkbh}-{dkName}", Brushes.Gray);

                            // 按目标选择
                            QueryFilter queryFilter = new QueryFilter();
                            queryFilter.WhereClause = $"{zoneField} = '{dkbh}' ";
                            featureLayer.Select(queryFilter);
                            // 按地块裁剪
                            Arcpy.Clip(yd, zone, clip);

                            // 汇总大、中、小类
                            Dictionary<string, double> dict = ComboTool.StatisticsPlus(clip, bmList, areaField, "合计", unit_xs);

                            // 复制sheet
                            ExcelTool.CopySheet(excel_path, "Sheet1", dkbh);

                            string excel_sheet = @$"{excel_path}\{dkbh}$";

                            // 汇总用地
                            Statistics(excel_sheet, dict, area, dkbh,dkName);
                        }

                        // 删除中间数据
                        Arcpy.Delect(clip);
                        // 取消当前选择
                        MapCtlTool.UnSelectAllFeature(zone);
                    }

                    pw.AddMessageMiddle(20, $"全用地统计");
                    if (true)
                    {
                        // 汇总大、中、小类
                        Dictionary<string, double> dict = ComboTool.StatisticsPlus(yd, bmList, areaField, "合计", unit_xs);


                        string excel_sheet = excel_path + @"\Sheet1$";

                        // 汇总用地
                        Statistics(excel_sheet, dict, 14.63819, "规划用地", "ff");
                    }

                });


                pw.AddMessageMiddle(100, "工具执行结束", Brushes.Blue);
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private void WriteWord(string excel_sheet, string dkbh, string dkName, string areaTotal)
        {
            // 获取工作薄、工作表
            string excelFile = ExcelTool.GetPath(excel_sheet);
            int sheetIndex = ExcelTool.GetSheetIndex(excel_sheet);
            // 打开工作薄
            Workbook wb = ExcelTool.OpenWorkbook(excelFile);
            // 打开工作表
            Worksheet sheet = wb.Worksheets[sheetIndex];

            Cells cells = sheet.Cells;

            for (int i = cells.MaxDataRow; i > 3; i--)
            {
                double mj = cells[i, 5].DoubleValue;
                cells[i, 6].Value = mj / (areaTotal.ToDouble()) * 100;
            }


            string area = cells[sheet.Cells.MaxDataRow, 5].StringValue;
            string pa = cells[sheet.Cells.MaxDataRow, 6].StringValue;
            string re = $"{dkbh}({dkName})" + "\r\n" + $"{dkbh}总面积{areaTotal}公顷。" + "\r\n" + $"范围内现状工矿及物流用地面积{area}公顷，占所在片区总面积的{pa}%。";
            cells["H2"].Value = re;

            // 保存
            wb.Save(excelFile);
            wb.Dispose();
        }


        // 按小类汇总
        private void Statistics(string excel_sheet, Dictionary<string, double> dict, double area, string dkbh, string dkName)
        {

            // 获取工作薄、工作表
            string excelFile =ExcelTool.GetPath(excel_sheet);
            int sheetIndex = ExcelTool.GetSheetIndex(excel_sheet);
            // 打开工作薄
            Workbook wb = ExcelTool.OpenWorkbook(excelFile);
            // 打开工作表
            Worksheet sheet = wb.Worksheets[sheetIndex];
            Cells cells = sheet.Cells;
            // 逐行处理
            double pg = dict.ContainsKey("已批未供用地") ? dict["已批未供用地"] : 0;
            double dx = dict.ContainsKey("低效用地") ? dict["低效用地"] : 0;
            double xz = dict.ContainsKey("闲置用地") ? dict["闲置用地"] : 0;
            double fj = dict.ContainsKey("其它非建设用地") ? dict["其它非建设用地"] : 0;
            double total = dict.ContainsKey("合计") ? dict["合计"] : 0;

            

            cells["C5"].Value = pg;
            cells["C6"].Value = dx;
            cells["C7"].Value = xz;
            cells["C8"].Value = fj;
            cells["C9"].Value = total;

            cells["D5"].Value = pg/area *100;
            cells["D6"].Value = dx / area * 100; 
            cells["D7"].Value = xz / area *100;
            cells["D8"].Value = fj / area *100;
            cells["D9"].Value = total / area *100;

            string areaStr = area.RoundWithFill(2);
            string totalStr = total.RoundWithFill(2);
            string prStr = (total / area * 100).RoundWithFill(2);

            string sm = $"{dkbh}({dkName})" +"\r\n"+$"{dkbh}总用地面积{areaStr}公顷，可开发用地合计{totalStr}公顷，占比{prStr}%";

            cells["E2"].Value = sm;

            // 保存
            wb.Save(excelFile);
            wb.Dispose();
        }
    }
}
